package cn.bocweb.spinning.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.ErrorBean;
import cn.bocweb.spinning.model.Bean.FirstMatchBean;
import cn.bocweb.spinning.model.Bean.SecondTestBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.common.BaseActivity;
import cn.bocweb.spinning.view.common.GlideCircle;
import de.greenrobot.event.EventBus;

public class LoginAcivity extends BaseActivity implements View.OnClickListener {


    @Bind(R.id.login_account)
    EditText loginAccount;
    @Bind(R.id.login_pwd)
    EditText loginPwd;
    @Bind(R.id.login_submit)
    Button loginSubmit;
    @Bind(R.id.login_forget_pwd)
    TextView loginForgetPwd;
    @Bind(R.id.login_register)
    Button loginRegister;
    @Bind(R.id.login_exit)
    RelativeLayout loginExit;

    UserPresenter presenter;
    boolean isClickable = true;
    int loginExitState = 0;
    int test_status;
    @Bind(R.id.login_icon)
    ImageView mLoginIcon;
    @Bind(R.id.login_nickname)
    TextView mLoginNickname;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        initClickBtn();
        initIntent();
        initInfo();
        presenter = new UserPresenterImp();
    }

    private void initInfo() {
        UserBean.DataEntity dataEntity = new UserBean.DataEntity();
        dataEntity.readInfoFromLocal(this);
        if (dataEntity.getNickname().isEmpty()) {
            mLoginNickname.setText("未登录");
        } else {
            mLoginNickname.setText(dataEntity.getNickname());
        }
        Glide.with(this)
                .load(dataEntity.getUthumb())
                .transform(new GlideCircle(this))
                .placeholder(R.mipmap.login_head)
                .error(R.mipmap.login_head)
                .into(mLoginIcon);

    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    private void initIntent() {
        Intent intent = getIntent();
        loginExitState = intent.getIntExtra(Constant.ACTIVITY_TO_LOGIN, 0);

    }

    private void initClickBtn() {
        loginForgetPwd.setOnClickListener(this);
        loginRegister.setOnClickListener(this);
        loginSubmit.setOnClickListener(this);
        loginExit.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_forget_pwd: {
                Intent intent = new Intent(this, ForgetPwdActivity.class);
                intent.putExtra(Constant.TO_FORGET_PWD, loginExitState);
                startActivityForResult(intent, loginExitState);
                break;
            }
            case R.id.login_register: {
                Intent intent = new Intent(this, RegisterActivity.class);
                intent.putExtra(Constant.TO_REGISTER, loginExitState);
                startActivityForResult(intent, loginExitState);
                finish();
                break;
            }
            case R.id.login_submit: {
                if (isClickable) {
                    showLoading();
                    isClickable = false;
                    String phone = loginAccount.getText().toString();
                    String pwd = loginPwd.getText().toString();
                    if (TextUtils.isEmpty(phone)) {
                        DeviceUtil.MyToast(this, "请输入手机号码...");
                        isClickable = true;
                        hideLoading();
                        return;
                    }
                    if (TextUtils.isEmpty(pwd)) {
                        DeviceUtil.MyToast(this, "请输入密码...");
                        isClickable = true;
                        hideLoading();
                        return;
                    }
                    if (!(phone.subSequence(0, 1).equals("1") && phone.length() == 11)) {
                        DeviceUtil.MyToast(this, "请输入正确的手机号...");
                        isClickable = true;
                        hideLoading();
                        return;
                    }
                    presenter.login(phone, pwd);
                }
                break;
            }
            case R.id.login_exit: {
                finish();
                break;
            }
        }

    }

    public void onEventMainThread(UserBean bean) {

        DeviceUtil.MyToast(this, bean.getMsg());
        if (bean.getReturn_code() == 0) {
            UserBean.DataEntity dataEntity = bean.getData();
            dataEntity.writeInfoIntoLocal(this);
            Intent intent;
            switch (loginExitState) {
                case Constant.INFODETAIL_TO_LOGIN: {
                    setResult(Constant.LOGIN_TO_MAIN);
                    finish();
                    break;
                }
                case Constant.SEQUENCE_TEST_SYNC: {
                    setResult(Constant.SEQUENCE_TEST_SYNC);
                    finish();
                    break;
                }
                case Constant.SEQUENCE_TEST_COLLECT: {
                    setResult(Constant.SEQUENCE_TEST_COLLECT);
                    finish();
                    break;
                }
                case Constant.TRAIN_TO_LOGIN: {
                    setResult(Constant.TRAIN_TO_LOGIN);
                    finish();
                    break;
                }
                case Constant.REWARD_TO_LOGIN: {
                    setResult(Constant.REWARD_TO_LOGIN);
                    finish();
                    break;
                }
                case Constant.TEST_RULE_BACK_LOGIN: {
                    setResult(Constant.TEST_RULE_BACK_LOGIN);
                    finish();
                    break;
                }
                case 100: {
                    intent = new Intent(LoginAcivity.this, ReadyTestActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                }
                case 101: {
                    presenter.getFirstMatch();
                    break;
                }
                case 102: {
                    presenter.secondTest(dataEntity.getUserid());
                    break;
                }
                default: {
                    finish();
                }
            }
        }
        isClickable = true;
        hideLoading();
    }

    public void onEventMainThread(SecondTestBean bean) {
        DeviceUtil.Log("now = " + System.currentTimeMillis() + " start = " + bean.getStart() + " end = " + bean.getEnd());
        if (bean.getReturn_code() == 0) {
            if (Long.parseLong(bean.getStart()) * 1000 < System.currentTimeMillis() &
                    Long.parseLong(bean.getEnd()) * 1000 > System.currentTimeMillis()) {
                Intent intent = new Intent(this, ReadyTestActivity.class);
                intent.putExtra(Constant.TO_READY_FIRST_TEST_ID, String.valueOf(bean.getId()));
                intent.putExtra(Constant.TO_SECOND_RULE_IS_SECOND_TEST, true);
                intent.putExtra(Constant.TO_SECOND_RULE_END_TIME, bean.getEnd());
                startActivity(intent);
                finish();
            } else if (Long.parseLong(bean.getStart()) * 1000 > System.currentTimeMillis()) {
                DeviceUtil.MyToast(this, "复赛时间未到（8月8日20:00-20:30）");
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
            } else if (Long.parseLong(bean.getEnd()) * 1000 < System.currentTimeMillis()) {
                DeviceUtil.MyToast(this, "复赛时间已过");
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
            }
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        }
    }

    public void onEventMainThread(FirstMatchBean bean) {
        if (bean.getReturn_code() == 0) {
            Intent intent = new Intent(this, ReadyTestActivity.class);
            intent.putExtra(Constant.TO_READY_FIRST_TEST_ID, bean.getId());
            intent.putExtra(Constant.TO_TEST_RANK_IF_FIRST, true);
            startActivity(intent);
            finish();
        } else {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        }
    }

    public void onEventMainThread(ErrorBean bean) {
        hideLoading();
        DeviceUtil.MyToast(this, bean.getErrorMsg());
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case Constant.TRAIN_TO_LOGIN: {
                setResult(Constant.TRAIN_TO_LOGIN);
                finish();
                break;
            }
            case Constant.SEQUENCE_TEST_COLLECT: {
                setResult(Constant.SEQUENCE_TEST_COLLECT);
                finish();
                break;
            }
            case Constant.SEQUENCE_TEST_SYNC: {
                setResult(Constant.SEQUENCE_TEST_SYNC);
                finish();
                break;
            }
            case Constant.INFODETAIL_TO_LOGIN: {
                setResult(Constant.LOGIN_TO_MAIN);
                finish();
                break;
            }
            case 0: {
                break;
            }
            default: {
                finish();
            }
        }
    }
}
